package com.java8feature.java8action.chapter11;

import com.java8feature.java8action.chapter11.entity.Shop;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 使用 completableFuture的工厂方法
 * @Author: yangzhiwei
 * @Date: 2021/6/15 16:51
 */
public class CompletableFutureTest1 {

    public double getPrice(String product) throws InterruptedException {
        return calculatePrice(product);
    }

    private double calculatePrice(String product) throws InterruptedException {
        Random r = new Random();
        int randNum =  r.nextInt(3);
        System.out.println(randNum);
        long startTime = System.currentTimeMillis();

        delay(randNum);
        System.out.println("get" + product + "Price Time ->" + (System.currentTimeMillis() - startTime));
        return r.nextDouble() * product.charAt(0) + product.charAt(1);
    }

    private void delay(Integer dalaySeconds) throws InterruptedException {
        if (dalaySeconds == null) {
           delay1SECNODS();
        } else {
           TimeUnit.SECONDS.sleep(dalaySeconds);
        }
    }

    private void delay1SECNODS() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
    }

    public Map normalTest() throws InterruptedException {
        Map<String, Double> map = new HashMap<>();
        System.out.println("==================start========================");
        map.put("applePrice", getPrice("apple"));
        map.put("orangePrice", getPrice("orange"));
        System.out.println("====================end=========================");
        return map;
    }

    public Future<Double> completableFuture() throws InterruptedException {
         return CompletableFuture.supplyAsync( () -> {
             try {
                 System.out.println(Thread.currentThread().getName());
                 throw new RuntimeException("auto Exception");
                 //return getPrice("apple");
             } catch (RuntimeException e) {
                 e.printStackTrace();
             } finally {
                 return 0.0;
             }
         });

        // CompletableFuture.supplyAsync()

    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CompletableFutureTest1 test = new CompletableFutureTest1();
        Map res = test.normalTest();
        System.out.println(res);

        Future res1 = test.completableFuture();
        System.out.println(res1.get());

        List<Shop> shops = Arrays.asList(new Shop("Best Price"),
                                        new Shop("LetsSaveBib"));


        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}
